<script>
    // 进销存 销售/出货表单
    Vue.component('stock-sales-form', {
        template: `
<el-dialog :visible.sync="dialogShow" width="1000px" @close="closeModal" :close-on-click-modal="false" :close-on-press-escape="false">
    <h3 slot="title">
        <span v-if="optType=='optSale'">销售出货</span>
        <span v-else-if="optType=='optSaleRefund'">销售退货</span>
        <span v-else-if="optType=='optPurchase'">采购进货</span>
        <span v-else-if="optType=='optPurchaseRefund'">采购退货</span>
    </h3>
    <el-form ref="form" :rules="formRules" :model="balanceForm" label-width="140px">

     <el-row>
        <el-col span="12">
            <el-form-item prop="house_id" required label="仓库">
                <el-select placeholder="请选择仓库" size='medium' v-model="balanceForm.house_id"  @change="houseSelect">
                    <el-option
                        v-for="item in stockWareHouseList"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                    </el-option>
                </el-select>
             </el-form-item>
        </el-col>
        <el-col span="12">
           <el-form-item label="账单分类" required>
             <el-select placeholder="全部分类" clearable filterable default-first-option v-model="balanceForm.category_id" filterable>
            <el-option-group
            v-for="cate in categoryList"
            :key="cate.title"
            :label="cate.title">
            <el-option
            v-for="item in cate.children"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
     </el-row>

     <el-row>
        <el-col span="12">
             <el-form-item label="项目">
                <el-select placeholder="选择项目" clearable filterable default-first-option v-model="balanceForm.project_id" size='medium'>
                    <el-option
                        v-for="item in projectList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col span="12">
            <el-form-item :label="storeStr">
               <el-select :placeholder="storeStr" clearable filterable default-first-option v-model="balanceForm.store_id">
            <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
        </el-col>
    </el-row>

     <el-row>
        <el-col span="12">
            <el-form-item label="时间">
                <el-date-picker class="datePicker" v-model="balanceForm.tally_date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
        </el-col>
        <el-col span="12">
            <el-form-item label="结算账户" required>
                <el-select placeholder="选择结算账户" clearable filterable default-first-option v-model="balanceForm.account_id" size='medium'>
                    <el-option
                        v-for="item in accountList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-col>
     </el-row>
     <el-row>
        <el-col span="12">
            <el-form-item label="备注">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" maxlength="255" show-word-limit placeholder="备注" v-model="balanceForm.memo" class="memoText"></el-input>
            </el-form-item>
        </el-col>
         <el-col span="12">
            <el-form-item :label="tipStr">
                <el-row>
                      <el-radio v-model='balanceForm.is_gua' :label='0'>否</el-radio>
                      <el-radio v-model='balanceForm.is_gua' :label='1'>是</el-radio>
                </el-row>
            </el-form-item>
         </el-col>
     </el-row>





     <!---复杂的表格 可动态选择产品--->
     <el-form-item label="">
     <el-table
      :data="productListData"
      style="width: 100%">
      <el-table-column
        prop="product_info"
        label="产品" >
          <template slot-scope="scope">
            <div>
             <el-select
                :value="productListData[scope.$index]['product_title']"
                filterable
                remote
                placeholder="请输入产品关键词"
                :remote-method="productSearch"
                @change="productSelect($event,scope.row,scope.$index)"
                size="mini"
                >
                <el-option
                  v-for="item in productFilterData"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </template>
      </el-table-column>
      <el-table-column
        prop="unit"
        label="单位">
         <template slot-scope="scope">
            <span>{{scope.row['product_unit']}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="pure_num"
        label="库存">
         <template slot-scope="scope">
            <span>{{scope.row['pure_num']}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="cost_price"
        label="销售价"
        v-if="saleOrPurchaseVal=='sale'"
        >
        <template slot-scope="scope">
            <el-input v-model="productListData[scope.$index]['sale_price']" size="mini" v-if="productListData[scope.$index]['product_id']" type="number" min="0" step="0.01" @blur="validPrice($event,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="purchase_price"
        label="采购价"
        v-if="saleOrPurchaseVal=='purchase'"
        >
        <template slot-scope="scope">
            <el-input v-model="productListData[scope.$index]['purchase_price']" size="mini" v-if="productListData[scope.$index]['product_id']" type="number" min="0" step="0.01" @blur="validPrice($event,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="num"
        label="数量">
        <template slot-scope="scope">
          <el-input v-model="productListData[scope.$index]['num']" size="mini" v-if="productListData[scope.$index]['product_id']" type="number" min="0" step="1" @blur="validNum($event,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="money"
        label="金额">
        <template slot-scope="scope">
            <span>{{scope.row['money']}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="opt"
        label="">
        <template slot-scope="scope">
          <el-button type="info" icon="el-icon-delete" circle  @click="delProductRow(scope.$index)" size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <p class="opt-row">
        <i class="el-icon-plus"></i>
        <el-button type="text" @click="addProductRow">添加一行</el-button>
    </p>
    <p class="t-r">
    数量合计：{{productTotalNum}}
    金额合计：{{productTotalMoney}}
    </p>
    </el-form-item>
   </el-form>

    <div slot="footer" class="dialog-footer">
    <el-button @click="closeModal">取 消</el-button>
    <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
    </div>
</el-dialog>
    `,
        props: ['dialog-show', 'sales-opt-type'],
        computed: {
            currentTallyId() {
                return this.$store.state.currentTallyId
            },
            currentTally() {
                return this.$store.state.currentTally
            },
            projectList() {
                return this.$store.state.projectList
            },
            stockWareHouseList() {
                return this.$store.state.stockWareHouseList
            },
            stockProductList() {
                return this.$store.state.stockProductList
            },
            accountList() {
                return this.$store.state.accountList
            },
            customList () {
                return this.$store.state.customList
            },
            gysList () {
                return this.$store.state.gysList
            },
            storeList() {
                if(this.optType==='optSale'||this.optType==='optSaleRefund') return this.customList;
                if(this.optType==='optPurchase'||this.optType==='optPurchaseRefund') return this.gysList
            },
            storeStr() {
                if(this.optType==='optSale'||this.optType==='optSaleRefund') return '客户';
                if(this.optType==='optPurchase'||this.optType==='optPurchaseRefund') return '供应商';
            },
            saleOrPurchaseVal() {
                if(this.optType==='optSale'||this.optType==='optSaleRefund') return 'sale';
                if(this.optType==='optPurchase'||this.optType==='optPurchaseRefund') return 'purchase';
            },
            saleTypeVal() {
                let val = 10
                switch (this.optType) {
                    case 'optSale':
                        val = 10;
                        break;
                    case 'optSaleRefund':
                        val = 20;
                        break;
                    case 'optPurchase':
                        val = 30;
                        break;
                    case 'optPurchaseRefund':
                        val = 40;
                        break;
                }
                return val;
            },
            categoryListIn() {
                return this.$store.state.categoryListIn
            },
            categoryListOut() {
                return this.$store.state.categoryListOut
            },
            categoryList() {
                if(this.optType==='optSale'||this.optType==='optPurchaseRefund'||this.optType==='optSaleRefund') return this.categoryListIn;
                else return this.categoryListOut
            },
            tipStr() {
                if(this.optType==='optSale'||this.optType==='optPurchaseRefund'||this.optType==='optSaleRefund') return '应收款';
                else return '应付款'
            },
        },
        watch: {
            dialogShow: {
                handler(newVal) {
                },
                deep: true,
                immediate: true
            },
            salesOptType: {
                handler(newVal) {
                    this.optType = newVal
                },
                deep: true,
                immediate: true
            }
        },
        data: function () {
            return {
                balanceForm: {
                    is_gua:0
                },
                optType: 'in', // 操作类型
                formRules: {
                    account_id: [
                        {required: true, message: '请选择结算账户'}
                    ],
                },
                productFilterData:[], // 过滤后显示的产品列表
                productListData: [
                    {},
                ], // 准备的产品列表数据
                productTotalNum:0, // 统计数据
                productTotalMoney:0,
            }
        },
        mounted:function(){
            this.productFilterData = this.stockProductList
        },
        methods: {
            closeModal() {
                this.$emit('modalClose', '')
            },
            // 重置
            resetForm() {
                this.productListData = [{}]
                this.balanceForm = {
                    is_gua:0
                }
                this.productTotalNum = 0
                this.productTotalMoney = 0
            },
            productSelect(productId, row, index) {
                let item = this.productFilterData.find((iv)=>{
                    return iv.id === productId;
                });
                let newValue = JSON.parse(JSON.stringify(this.productListData[index]))
                let that = this
                newValue['product_id'] =  item['id']
                newValue['product_title'] =  item['title']
                newValue['pure_num'] = item['pure_num'] ? item['pure_num'] : '-'
                newValue['num'] = 1
                that.getProductInfo(productId).then((prodInfo) => {
                    newValue['product_spec'] =  prodInfo['spec']
                    newValue['product_unit'] =  prodInfo['unit']
                    newValue['cost_price'] =  prodInfo['cost_price']
                    newValue['sale_price'] =  prodInfo['sale_price']
                    newValue['purchase_price'] =  prodInfo['purchase_price']
                    // 刷新数据
                    this.$set(this.productListData,index,newValue)
                    this.calRowMoney(index)
                })
            },
            getProductInfo(productId) {
                let that = this
                let getUrl = '/api/stock-product/info'
                let params = {
                    tally_id : that.currentTallyId,
                    product_id : productId
                }
                return new Promise((resolve, reject) => {
                    axios.get(getUrl,{
                        method: 'get',
                        headers: {'token': loginToken},
                        params: params
                    }).then(function(res) {
                        if(res.data.status === 'success'){
                            resolve(res.data.data)
                        }else{
                            resolve({})
                        }
                    })
                }).catch(err=>{
                    reject(err)
                })
            },
            validPrice(e,index) {
                if(this.saleOrPurchaseVal === 'sale') {
                    let number = this.productListData[index]['sale_price']
                    number = parseFloat(number).toFixed(2)
                    this.productListData[index]['sale_price'] = number
                }else {
                    let number = this.productListData[index]['purchase_price']
                    number = parseFloat(number).toFixed(2)
                    this.productListData[index]['purchase_price'] = number
                }
                this.calRowMoney(index)
            },
            validNum(e,index) {
                let number = this.productListData[index]['num']
                number = parseFloat(number).toFixed(2)
                this.productListData[index]['num'] = number
                this.calRowMoney(index)
            },
            // 计算分录金额
            calRowMoney(index) {
                let price = 0
                if(this.saleOrPurchaseVal === 'sale') {
                    price = this.productListData[index]['sale_price']
                }else {
                    price = this.productListData[index]['purchase_price']
                }

                let num = this.productListData[index]['num']
                let pureNum = this.productListData[index]['pure_num']

                // console.log(num,pureNum)
                // let num = pure_num;
                // console.log(  parseFloat(num) > parseFloat(pureNum))
                if(!isNaN(pureNum) && parseFloat(num) > parseFloat(pureNum)) {
                    num = pureNum
                    this.productListData[index]['num'] = pureNum
                }
                this.productListData[index]['money'] = (price * num ).toFixed(2)
                let newValue = JSON.parse(JSON.stringify(this.productListData[index]))
                this.$set(this.productListData,index,newValue)

                this.calTotal()
            },
            // 计算总计金额
            calTotal() {
                let totalNum = 0
                let totalMoney = 0
                this.productListData.forEach((item) => {
                    if(item['product_id']) {
                        totalNum = totalNum + parseFloat(item['num'])
                        totalMoney = totalMoney + parseFloat(item['money'])
                    }
                })
                this.productTotalNum = parseFloat(totalNum).toFixed(2)
                this.productTotalMoney = parseFloat(totalMoney).toFixed(2)
            },
            houseSelect(houseId) {
                let item = this.stockWareHouseList.find((iv)=>{
                    return iv.id === houseId;
                });
                this.balanceForm['house_id'] = item['id'];
                this.balanceForm['house_title'] = item['title'];
                // 获取该仓库下的库存产品列表
                if(this.optType === 'optSaleRefund' || this.optType === 'optPurchase') {
                    this.getProductList() // 全局产品
                }else if(this.optType === 'optSale' || this.optType === 'optPurchaseRefund') {
                    this.getHouseProductList(item['id']) // 仓库下产品
                    this.productListData = [{}]   // 清空产品数据
                }
            },
            getProductList() {
                let that = this
                let getUrl = '/api/stock-product/all'
                let params = {
                    tally_id : that.currentTallyId,
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.stockProductList = res.data.data
                        that.productFilterData = res.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            getHouseProductList(houseId) {
                let that = this
                let getUrl = '/api/stock-warehouse/product-all'
                let params = {
                    tally_id : that.currentTallyId,
                    house_id : houseId
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.stockProductList = res.data.data
                        that.productFilterData = res.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            productSearch(query) {
                let that = this
                if(query === '') {
                    that.productFilterData = that.stockProductList
                }else {
                    if(this.optType === 'optSaleRefund' || this.optType === 'optPurchase') {
                        this.productSearchGlobal(query)  // 全局产品搜索
                    }else if(this.optType === 'optSale' || this.optType === 'optPurchaseRefund') {
                        this.productSearchHouse(query)  // 仓库下产品搜索
                    }
                }
            },
            productSearchGlobal(keywords) {
                let that = this
                let getUrl = '/api/stock-product/lists'
                let params = {
                    tally_id : that.currentTallyId,
                    keywords : encodeURIComponent(keywords)
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.productFilterData = res.data.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            productSearchHouse(keywords) {
                let that = this
                let getUrl = '/api/stock-warehouse/product-search'
                let params = {
                    tally_id : that.currentTallyId,
                    house_id : that.balanceForm['house_id'],
                    keywords : encodeURIComponent(keywords)
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.productFilterData = res.data.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            addProductRow() {
                this.productListData.push({})
            },
            delProductRow(index)  {
                this.productListData.splice(index,1)
            },
            handleFormSubmit() {
                let that = this
                let postUrl = '/api/stock-record/add'
                if(that.productListData.length < 1) {
                    that.$message({
                        type: 'error',
                        message: '请先填写完整产品信息'
                    })
                    return false;
                }
                that.balanceForm.tally_id = that.currentTallyId
                that.balanceForm.sales_type = that.saleTypeVal
                that.balanceForm.product_detail = that.productListData
                axios.post(postUrl, that.balanceForm, {
                    headers: {'token': loginToken},
                }).then(function (res) {
                    if (res.data.status === 'success') {
                        that.$message({
                            type: 'success',
                            message: '数据保存成功'
                        });
                        that.$emit('modalClose', 'refresh')
                    } else {
                        that.$message({
                            type: 'error',
                            message: '解析数据失败:' + res.data.error_message
                        })
                    }
                })
            },
        }
    })
</script>
<style>
    .memoText {
        width: 300px;
    }
    .t-r {
        text-align: right;
    }
    .opt-row{
        color: #409EFF;
    }
</style>
